<template>
  <div class="search">
    <div class="search-container">
      <van-icon name="wap-home-o" class="icon-return" @click="$router.go(-1)" />
      <form action="/">
        <van-search
          autofocus="true"
          class="search-input"
          v-model="value"
          shape="round"
          background="#4fc08d"
          placeholder="请输入搜索关键词"
          @search="onSearch(value)"
          @focus="isResultShow = false"
        />
      </form>
    </div>

    <!-- 搜索栏 -->
    <!-- 搜索结果 -->
    <search-result :searchText="value" v-if="isResultShow" />

    <!-- 联想建议 -->
    <search-suggest
      v-else-if="value"
      :searchText="value"
      @search="onSearch"
    ></search-suggest>

    <!-- 搜索历史 -->
    <search-history
     :searchHistores="searchHistories"
      v-else
      @search='onSearch'></search-history>
  </div>
</template>

<script>
import searchSuggest from "./component/searchSuggest.vue";
import searchHistory from "./component/searchHistory.vue";
import searchResult from "./component/searchResult.vue";
import {setItem,getItem} from '@/util/storage.js'
export default {
  components: {
    searchSuggest,
    searchHistory,
    searchResult,
  },
  data() {
    return {
      value: "",
      isResultShow: false, //控制搜索结果的显示状态
      //搜索历史数据
      searchHistories: getItem('search-histories') || [],
    };
  },
  methods: {
    onSearch(value) {
      this.value = value;

      // // 判断搜索是否有重复
      const index = this.searchHistories.indexOf(value);
      if (index !== -1) {
        //把重复项移除掉
        this.searchHistories.splice(index, 1);
      }

      // //把最新的搜索历史放在顶部
      this.searchHistories.unshift(value);
       setItem("search-histories", this.searchHistories);
      // 展示搜索结果
      this.isResultShow = true;
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  .search-container {
    position: relative;
    .icon-return {
      position: absolute;
      font-size: 30px;
      line-height: 54px;
      color: #fff;
    }
    .search-input {
      background-color: rgb(73, 160, 175) !important;
      padding-left: 40px;
    }
  }
}
</style>